<!DOCTYPE html>



  


<html class="theme-next gemini use-motion" lang="zh-Hans">
<head>
  <meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"/>
<meta name="theme-color" content="#222">









<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />
















  
  
  <link href="/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css" />







<link href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css" />

<link href="/css/main.css?v=5.1.4" rel="stylesheet" type="text/css" />


  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16-next.png?v=5.1.4">


  <link rel="mask-icon" href="/images/logo.svg?v=5.1.4" color="#222">





  <meta name="keywords" content="xlwt使用," />










<meta name="description" content="最近做项目要使用到导出Excel的表格. 正好Django有xlwt这个库.今天给大家分享一下如何使用这个库的. 因为django不自带.需要我们自己安装这个库 1pip install xlwt 安装好只有我们就可以开始写我们的代码了. 案例:我们以导出客户贷款信息的模块为列来讲解xlwt的使用. 首先在自己的视图函数中导入模块,需要使用到如下的两个模块 1234# 1.导出excel的库imp">
<meta name="keywords" content="xlwt使用">
<meta property="og:type" content="article">
<meta property="og:title" content="django使用xlwt导出excel文件">
<meta property="og:url" content="http://yoursite.com/2018/08/06/django使用xlwt导出excel文件/index.html">
<meta property="og:site_name" content="Mr. Lee&#39;s blog">
<meta property="og:description" content="最近做项目要使用到导出Excel的表格. 正好Django有xlwt这个库.今天给大家分享一下如何使用这个库的. 因为django不自带.需要我们自己安装这个库 1pip install xlwt 安装好只有我们就可以开始写我们的代码了. 案例:我们以导出客户贷款信息的模块为列来讲解xlwt的使用. 首先在自己的视图函数中导入模块,需要使用到如下的两个模块 1234# 1.导出excel的库imp">
<meta property="og:locale" content="zh-Hans">
<meta property="og:image" content="http://yoursite.com/2018/08/06/django使用xlwt导出excel文件/daik.png">
<meta property="og:image" content="http://yoursite.com/2018/08/06/django使用xlwt导出excel文件/jk.png">
<meta property="og:updated_time" content="2018-08-06T12:50:39.000Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="django使用xlwt导出excel文件">
<meta name="twitter:description" content="最近做项目要使用到导出Excel的表格. 正好Django有xlwt这个库.今天给大家分享一下如何使用这个库的. 因为django不自带.需要我们自己安装这个库 1pip install xlwt 安装好只有我们就可以开始写我们的代码了. 案例:我们以导出客户贷款信息的模块为列来讲解xlwt的使用. 首先在自己的视图函数中导入模块,需要使用到如下的两个模块 1234# 1.导出excel的库imp">
<meta name="twitter:image" content="http://yoursite.com/2018/08/06/django使用xlwt导出excel文件/daik.png">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/',
    scheme: 'Gemini',
    version: '5.1.4',
    sidebar: {"position":"left","display":"post","offset":12,"b2t":false,"scrollpercent":false,"onmobile":false},
    fancybox: true,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    duoshuo: {
      userId: '0',
      author: 'Author'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="http://yoursite.com/2018/08/06/django使用xlwt导出excel文件/"/>





  <title>django使用xlwt导出excel文件 | Mr. Lee's blog</title>
  








</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/"  class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">Mr. Lee's blog</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <h1 class="site-subtitle" itemprop="description">知识改变命运,技术成就梦想</h1>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br />
            
            首页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/archives/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br />
            
            归档
          </a>
        </li>
      
        
        <li class="menu-item menu-item-tags">
          <a href="/tags/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-tags"></i> <br />
            
            标签
          </a>
        </li>
      
        
        <li class="menu-item menu-item-about">
          <a href="/about/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-user"></i> <br />
            
            关于
          </a>
        </li>
      
        
        <li class="menu-item menu-item-commonweal">
          <a href="/404.html" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-heartbeat"></i> <br />
            
            公益404
          </a>
        </li>
      

      
        <li class="menu-item menu-item-search">
          
            <a href="javascript:;" class="popup-trigger">
          
            
              <i class="menu-item-icon fa fa-search fa-fw"></i> <br />
            
            搜索
          </a>
        </li>
      
    </ul>
  

  
    <div class="site-search">
      
  <div class="popup search-popup local-search-popup">
  <div class="local-search-header clearfix">
    <span class="search-icon">
      <i class="fa fa-search"></i>
    </span>
    <span class="popup-btn-close">
      <i class="fa fa-times-circle"></i>
    </span>
    <div class="local-search-input-wrapper">
      <input autocomplete="off"
             placeholder="搜索..." spellcheck="false"
             type="text" id="local-search-input">
    </div>
  </div>
  <div id="local-search-result"></div>
</div>



    </div>
  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="http://yoursite.com/2018/08/06/django使用xlwt导出excel文件/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="Mr. Lee">
      <meta itemprop="description" content="">
      <meta itemprop="image" content="/avatar.png">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="Mr. Lee's blog">
    </span>

    
      <header class="post-header">

        
        
          <h2 class="post-title" itemprop="name headline">django使用xlwt导出excel文件</h2>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              
              <time title="创建于" itemprop="dateCreated datePublished" datetime="2018-08-06T20:24:29+08:00">
                2018-08-06
              </time>
            

            

            
          </span>

          

          
            
          

          
          

          

          
            <div class="post-wordcount">
              
                
                <span class="post-meta-item-icon">
                  <i class="fa fa-file-word-o"></i>
                </span>
                
                  <span class="post-meta-item-text">字数统计&#58;</span>
                
                <span title="字数统计">
                  1,063
                </span>
              

              
                <span class="post-meta-divider">|</span>
              

              
                <span class="post-meta-item-icon">
                  <i class="fa fa-clock-o"></i>
                </span>
                
                  <span class="post-meta-item-text">阅读时长 &asymp;</span>
                
                <span title="阅读时长">
                  5
                </span>
              
            </div>
          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <h4 id="最近做项目要使用到导出Excel的表格-正好Django有xlwt这个库"><a href="#最近做项目要使用到导出Excel的表格-正好Django有xlwt这个库" class="headerlink" title="最近做项目要使用到导出Excel的表格. 正好Django有xlwt这个库."></a>最近做项目要使用到导出Excel的表格. 正好Django有<code>xlwt</code>这个库.</h4><p>今天给大家分享一下如何使用这个库的.</p>
<p>因为django不自带.需要我们自己安装这个库</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">pip install xlwt</span><br></pre></td></tr></table></figure>
<p>安装好只有我们就可以开始写我们的代码了.</p>
<p>案例:我们以导出客户贷款信息的模块为列来讲解xlwt的使用.</p>
<p>首先在自己的视图函数中导入模块,需要使用到如下的两个模块</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"># 1.导出excel的库</span><br><span class="line">import xlwt</span><br><span class="line"># 2.实现了在内存中读写bytes</span><br><span class="line">from io import BytesIO</span><br></pre></td></tr></table></figure>
<blockquote>
<h6 id="BytesIO"><a href="#BytesIO" class="headerlink" title="BytesIO"></a>BytesIO</h6><p>StringIO操作的只能是str，如果要操作二进制数据，就需要使用BytesIO。</p>
<p>BytesIO实现了在内存中读写bytes，我们创建一个BytesIO，然后写入一些bytes：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line">&gt;&gt;&gt;&gt; from io import BytesIO</span><br><span class="line">&gt;&gt;&gt;&gt; f = BytesIO()</span><br><span class="line">&gt;&gt;&gt;&gt; f.write(&apos;中文&apos;.encode(&apos;utf-8&apos;))</span><br><span class="line">&gt;6</span><br><span class="line">&gt;&gt;&gt;&gt; print(f.getvalue())</span><br><span class="line">&gt;b&apos;\xe4\xb8\xad\xe6\x96\x87&apos;</span><br><span class="line">&gt;</span><br></pre></td></tr></table></figure>
</blockquote>
<blockquote>
<p>请注意，写入的不是str，而是经过UTF-8编码的bytes。</p>
<p>和StringIO类似，可以用一个bytes初始化BytesIO，然后，像读文件一样读取：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">&gt;&gt;&gt;&gt; from io import BytesIO</span><br><span class="line">&gt;&gt;&gt;&gt; f = BytesIO(b&apos;\xe4\xb8\xad\xe6\x96\x87&apos;)</span><br><span class="line">&gt;&gt;&gt;&gt; f.read()</span><br><span class="line">&gt;b&apos;\xe4\xb8\xad\xe6\x96\x87&apos;</span><br><span class="line">&gt;</span><br></pre></td></tr></table></figure>
</blockquote>
<blockquote>
<h6 id="小结"><a href="#小结" class="headerlink" title="小结"></a>小结</h6><p>StringIO和BytesIO是在内存中操作str和bytes的方法，使得和读写文件具有一致的接口。</p>
</blockquote>
<p>我们定义导出函数<code>export_excel</code></p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># 导出excel数据</span></span><br><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">export_excel</span><span class="params">(request)</span>:</span></span><br><span class="line">    <span class="comment"># 设置HTTPResponse的类型</span></span><br><span class="line">    response = HttpResponse(content_type=<span class="string">'application/vnd.ms-excel'</span>)</span><br><span class="line">    response[<span class="string">'Content-Disposition'</span>] = <span class="string">'attachment;filename=order.xls'</span></span><br><span class="line">    <span class="comment"># 创建一个文件对象</span></span><br><span class="line">    wb = xlwt.Workbook(encoding=<span class="string">'utf8'</span>)</span><br><span class="line">    <span class="comment"># 创建一个sheet对象</span></span><br><span class="line">    sheet = wb.add_sheet(<span class="string">'order-sheet'</span>)</span><br><span class="line">    </span><br><span class="line">	<span class="comment"># 设置文件头的样式,这个不是必须的可以根据自己的需求进行更改</span></span><br><span class="line">    style_heading = xlwt.easyxf(<span class="string">"""</span></span><br><span class="line"><span class="string">            font:</span></span><br><span class="line"><span class="string">                name Arial,</span></span><br><span class="line"><span class="string">                colour_index white,</span></span><br><span class="line"><span class="string">                bold on,</span></span><br><span class="line"><span class="string">                height 0xA0;</span></span><br><span class="line"><span class="string">            align:</span></span><br><span class="line"><span class="string">                wrap off,</span></span><br><span class="line"><span class="string">                vert center,</span></span><br><span class="line"><span class="string">                horiz center;</span></span><br><span class="line"><span class="string">            pattern:</span></span><br><span class="line"><span class="string">                pattern solid,</span></span><br><span class="line"><span class="string">                fore-colour 0x19;</span></span><br><span class="line"><span class="string">            borders:</span></span><br><span class="line"><span class="string">                left THIN,</span></span><br><span class="line"><span class="string">                right THIN,</span></span><br><span class="line"><span class="string">                top THIN,</span></span><br><span class="line"><span class="string">                bottom THIN;</span></span><br><span class="line"><span class="string">            """</span>)</span><br><span class="line">    </span><br><span class="line">    <span class="comment"># 写入文件标题</span></span><br><span class="line">    sheet.write(<span class="number">0</span>,<span class="number">0</span>,<span class="string">'申请编号'</span>,style_heading)</span><br><span class="line">    sheet.write(<span class="number">0</span>,<span class="number">1</span>,<span class="string">'客户名称'</span>,style_heading)</span><br><span class="line">    sheet.write(<span class="number">0</span>,<span class="number">2</span>,<span class="string">'联系方式'</span>,style_heading)</span><br><span class="line">    sheet.write(<span class="number">0</span>,<span class="number">3</span>,<span class="string">'身份证号码'</span>,style_heading)</span><br><span class="line">    sheet.write(<span class="number">0</span>,<span class="number">4</span>,<span class="string">'办理日期'</span>,style_heading)</span><br><span class="line">    sheet.write(<span class="number">0</span>,<span class="number">5</span>,<span class="string">'处理人'</span>,style_heading)</span><br><span class="line">    sheet.write(<span class="number">0</span>,<span class="number">6</span>,<span class="string">'处理状态'</span>,style_heading)</span><br><span class="line">    sheet.write(<span class="number">0</span>,<span class="number">7</span>,<span class="string">'处理时间'</span>,style_heading)</span><br><span class="line"></span><br><span class="line">    <span class="comment"># 写入数据</span></span><br><span class="line">    data_row = <span class="number">1</span></span><br><span class="line">    <span class="comment"># UserTable.objects.all()这个是查询条件,可以根据自己的实际需求做调整.</span></span><br><span class="line">    <span class="keyword">for</span> i <span class="keyword">in</span> UserTable.objects.all():</span><br><span class="line">     	<span class="comment"># 格式化datetime</span></span><br><span class="line">        pri_time = i.pri_date.strftime(<span class="string">'%Y-%m-%d'</span>)</span><br><span class="line">        oper_time = i.operating_time.strftime(<span class="string">'%Y-%m-%d'</span>)</span><br><span class="line">        sheet.write(data_row,<span class="number">0</span>,i.loan_id)</span><br><span class="line">        sheet.write(data_row,<span class="number">1</span>,i.name)</span><br><span class="line">        sheet.write(data_row,<span class="number">2</span>,i.user_phone)</span><br><span class="line">        sheet.write(data_row,<span class="number">3</span>,i.user_card)</span><br><span class="line">        sheet.write(data_row,<span class="number">4</span>,pri_time)</span><br><span class="line">        sheet.write(data_row,<span class="number">5</span>,i.emp.emp_name)</span><br><span class="line">        sheet.write(data_row,<span class="number">6</span>,i.statu.statu_name)</span><br><span class="line">        sheet.write(data_row,<span class="number">7</span>,oper_time)</span><br><span class="line">        data_row = data_row + <span class="number">1</span></span><br><span class="line"></span><br><span class="line">    <span class="comment"># 写出到IO</span></span><br><span class="line">    output = BytesIO()</span><br><span class="line">    wb.save(output)</span><br><span class="line">    <span class="comment"># 重新定位到开始</span></span><br><span class="line">    output.seek(<span class="number">0</span>)</span><br><span class="line">    response.write(output.getvalue())</span><br><span class="line">    <span class="keyword">return</span> response</span><br></pre></td></tr></table></figure>
<h5 id="补充一下我们的model"><a href="#补充一下我们的model" class="headerlink" title="补充一下我们的model"></a>补充一下我们的model</h5><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br></pre></td><td class="code"><pre><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">UserTable</span><span class="params">(models.Model)</span>:</span></span><br><span class="line">    user_id = models.AutoField(primary_key=<span class="keyword">True</span>)</span><br><span class="line">    payment = models.ForeignKey(PaymentTable, models.DO_NOTHING, blank=<span class="keyword">True</span>, null=<span class="keyword">True</span>)</span><br><span class="line">    name = models.CharField(max_length=<span class="number">256</span>)</span><br><span class="line">    loa_loan = models.ForeignKey(LoantypeTable, models.DO_NOTHING, blank=<span class="keyword">True</span>, null=<span class="keyword">True</span>)</span><br><span class="line">    statu = models.ForeignKey(StatuTable, models.DO_NOTHING, blank=<span class="keyword">True</span>, null=<span class="keyword">True</span>)</span><br><span class="line">    user_card = models.CharField(max_length=<span class="number">256</span>, blank=<span class="keyword">True</span>, null=<span class="keyword">True</span>)</span><br><span class="line">    loan_id = models.CharField(max_length=<span class="number">256</span>, blank=<span class="keyword">True</span>, null=<span class="keyword">True</span>)</span><br><span class="line">    user_phone = models.CharField(max_length=<span class="number">256</span>, blank=<span class="keyword">True</span>, null=<span class="keyword">True</span>) </span><br><span class="line">    principal = models.CharField(max_length=<span class="number">256</span>, blank=<span class="keyword">True</span>, null=<span class="keyword">True</span>)  <span class="comment"># 逾期金额</span></span><br><span class="line">    pri_date = models.DateField(blank=<span class="keyword">True</span>, null=<span class="keyword">True</span>) <span class="comment"># 贷款日期</span></span><br><span class="line">    emp = models.ForeignKey(EmpTable, models.DO_NOTHING, blank=<span class="keyword">True</span>, null=<span class="keyword">True</span>) <span class="comment"># 贷款处理人</span></span><br><span class="line">    wallet = models.CharField(max_length=<span class="number">256</span>, blank=<span class="keyword">True</span>, null=<span class="keyword">True</span>) </span><br><span class="line">    operating_time = models.DateField(auto_now=<span class="keyword">True</span>)  <span class="comment"># 贷款处理时间</span></span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">to_dict</span><span class="params">(self)</span>:</span></span><br><span class="line">        <span class="keyword">return</span> &#123;</span><br><span class="line">            <span class="string">'user_id'</span> : self.user_id,</span><br><span class="line">            <span class="string">'loan_id'</span> : self.loan_id,</span><br><span class="line">            <span class="string">'name'</span> : self.name,</span><br><span class="line">            <span class="string">'phone'</span> : self.user_phone,</span><br><span class="line">            <span class="string">'card'</span> : self.user_card,</span><br><span class="line">            <span class="string">'date'</span> : self.pri_date.strftime(<span class="string">'%Y-%m-%d'</span>),</span><br><span class="line">            <span class="string">'deal_peo'</span> : self.emp.emp_name,</span><br><span class="line">            <span class="string">'status'</span> : self.statu.statu_name,</span><br><span class="line">            <span class="string">'deal_time'</span> : datetime.datetime.now().strftime(<span class="string">'%Y-%m-%d'</span>)</span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">    <span class="class"><span class="keyword">class</span> <span class="title">Meta</span>:</span></span><br><span class="line">        managed = <span class="keyword">False</span></span><br><span class="line">        db_table = <span class="string">'user_table'</span></span><br></pre></td></tr></table></figure>
<h5 id="调取后台函数"><a href="#调取后台函数" class="headerlink" title="调取后台函数"></a>调取后台函数</h5><p>前端的操作.重要的就一句话 (可以使用ajax或者a标签的herf属性)去掉用我们的后台视图函数</p>
<figure class="highlight html"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="tag">&lt;<span class="name">a</span> <span class="attr">href</span>=<span class="string">"/admin/export_excel/"</span>&gt;</span><span class="tag">&lt;<span class="name">button</span>  <span class="attr">type</span>=<span class="string">"button"</span> <span class="attr">class</span>=<span class="string">"btnStyle"</span> &gt;</span>导出excel<span class="tag">&lt;/<span class="name">button</span>&gt;</span><span class="tag">&lt;/<span class="name">a</span>&gt;</span></span><br></pre></td></tr></table></figure>
<p>前端的效果</p>
<p><img src="/2018/08/06/django使用xlwt导出excel文件/daik.png" alt="ai"></p>
<p>最后实现导出的效果.标题是加红色了的,就是上面我们设置的样式.</p>
<p><img src="/2018/08/06/django使用xlwt导出excel文件/jk.png" alt=""></p>
<p>本文原创出品.欢迎收藏转载!!!!</p>
<blockquote>
<p><strong>作 者:</strong> lizhonglin</p>
<p><strong>github:</strong> <a href="https://github.com/Leezhonglin/" target="_blank" rel="noopener">https://github.com/Leezhonglin/</a></p>
<p><strong>blog:</strong> <a href="https://leezhonglin.github.io/" target="_blank" rel="noopener">https://leezhonglin.github.io/</a></p>
</blockquote>

      
    </div>
    
    
    

    

    
      <div>
        <div style="padding: 10px 0; margin: 20px auto; width: 90%; text-align: center;">
  <div></div>
  <button id="rewardButton" disable="enable" onclick="var qr = document.getElementById('QR'); if (qr.style.display === 'none') {qr.style.display='block';} else {qr.style.display='none'}">
    <span>打赏</span>
  </button>
  <div id="QR" style="display: none;">

    
      <div id="wechat" style="display: inline-block">
        <img id="wechat_qr" src="/WechatIMG26.jpeg" alt="Mr. Lee 微信支付"/>
        <p>微信支付</p>
      </div>
    

    

    

  </div>
</div>

      </div>
    

    

    <div>
      
        <div>
    
        <div style="text-align:center;color: #ccc;font-size:14px;">
            -------------本文结束
            <i class="fa fa-paw"></i>
            感谢您的阅读-------------
        </div>
    
</div>
      
    </div>

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/tags/xlwt使用/" rel="tag"><i class="fa fa-tag"></i> xlwt使用</a>
          
        </div>
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/2018/07/07/Scrapy分布式爬虫-爬取人人车全国二手车车辆信息/" rel="next" title="Scrapy分布式爬虫-爬取人人车全国二手车车辆信息">
                <i class="fa fa-chevron-left"></i> Scrapy分布式爬虫-爬取人人车全国二手车车辆信息
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/2018/08/07/Django中多条件查询解决方法/" rel="prev" title="Django中多条件查询解决方法">
                Django中多条件查询解决方法 <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>



    <div class="post-spread">
      
    </div>
  </div>


          </div>
          


          

  



        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap">
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview-wrap">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview-wrap sidebar-panel">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
            
              <img class="site-author-image" itemprop="image"
                src="/avatar.png"
                alt="Mr. Lee" />
            
              <p class="site-author-name" itemprop="name">Mr. Lee</p>
              <p class="site-description motion-element" itemprop="description"></p>
          </div>

          <nav class="site-state motion-element">

            
              <div class="site-state-item site-state-posts">
              
                <a href="/archives/">
              
                  <span class="site-state-item-count">33</span>
                  <span class="site-state-item-name">日志</span>
                </a>
              </div>
            

            

            
              
              
              <div class="site-state-item site-state-tags">
                <a href="/tags/index.html">
                  <span class="site-state-item-count">30</span>
                  <span class="site-state-item-name">标签</span>
                </a>
              </div>
            

          </nav>

          

          
            <div class="links-of-author motion-element">
                
                  <span class="links-of-author-item">
                    <a href="https://github.com/Leezhonglin" target="_blank" title="GitHub">
                      
                        <i class="fa fa-fw fa-github"></i>GitHub</a>
                  </span>
                
                  <span class="links-of-author-item">
                    <a href="mailto:380604322@qq.com" target="_blank" title="E-Mail">
                      
                        <i class="fa fa-fw fa-envelope"></i>E-Mail</a>
                  </span>
                
            </div>
          

          
          

          
          
            <div class="links-of-blogroll motion-element links-of-blogroll-block">
              <div class="links-of-blogroll-title">
                <i class="fa  fa-fw fa-link"></i>
                友情链接
              </div>

              <ul class="links-of-blogroll-list">

                
                    <span class="links-of-author-item" style="text-align:center">
                      <a href="https://my.csdn.net/jackfrued/" title="大 神" target="_blank">
                        大 神
                      </a>
                    </span>
                
                    <span class="links-of-author-item" style="text-align:center">
                      <a href="https://blog.csdn.net/qq_33196814" title="CSDN" target="_blank">
                        CSDN
                      </a>
                    </span>
                
                    <span class="links-of-author-item" style="text-align:center">
                      <a href="http://www.python.org" title="python" target="_blank">
                        python
                      </a>
                    </span>
                
                    <span class="links-of-author-item" style="text-align:center">
                      <a href="http://redisdoc.com/" title="redis" target="_blank">
                        redis
                      </a>
                    </span>
                

              </ul>


            </div>
          

          

        </div>
      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-4"><a class="nav-link" href="#最近做项目要使用到导出Excel的表格-正好Django有xlwt这个库"><span class="nav-number">1.</span> <span class="nav-text">最近做项目要使用到导出Excel的表格. 正好Django有xlwt这个库.</span></a><ol class="nav-child"><li class="nav-item nav-level-6"><a class="nav-link" href="#BytesIO"><span class="nav-number">1.0.1.</span> <span class="nav-text">BytesIO</span></a></li><li class="nav-item nav-level-6"><a class="nav-link" href="#小结"><span class="nav-number">1.0.2.</span> <span class="nav-text">小结</span></a></li></ol></li><li class="nav-item nav-level-5"><a class="nav-link" href="#补充一下我们的model"><span class="nav-number">1.1.</span> <span class="nav-text">补充一下我们的model</span></a></li><li class="nav-item nav-level-5"><a class="nav-link" href="#调取后台函数"><span class="nav-number">1.2.</span> <span class="nav-text">调取后台函数</span></a></li></ol></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <script async src="//busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script>
<div class="copyright">&copy; <span itemprop="copyrightYear">2019</span>
  <span class="with-love">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">Mr. Lee</span>

  
</div>


  <span class="post-meta-divider">|</span>



  <div class="powered-by">由 <a class="theme-link" target="_blank" href="https://github.com/Leezhonglin">Leezhonglin</a> 提供技术支持</div>



  <span class="post-meta-divider">|</span>


<div class="powered-by">
<i class="fa fa-user-md"></i><span id="busuanzi_container_site_uv">
  本站访客数:<span id="busuanzi_value_site_uv"></span>
</span>


  <span class="post-meta-divider">|</span>


<span id="busuanzi_container_site_pv">
    本站总访问量:<span id="busuanzi_value_site_pv"></span>次
</span>


  <span class="post-meta-divider">|</span>


</div>


<div class="theme-info">
  <div class="powered-by"></div>
  <span class="post-count">博客全站共:64.5k字</span>
</div>


  <span class="post-meta-divider">|</span>




        







        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
      </div>
    

    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  












  
  
    <script type="text/javascript" src="/lib/jquery/index.js?v=2.1.3"></script>
  

  
  
    <script type="text/javascript" src="/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>
  

  
  
    <script type="text/javascript" src="/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>
  


  


  <script type="text/javascript" src="/js/src/utils.js?v=5.1.4"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=5.1.4"></script>



  
  


  <script type="text/javascript" src="/js/src/affix.js?v=5.1.4"></script>

  <script type="text/javascript" src="/js/src/schemes/pisces.js?v=5.1.4"></script>



  
  <script type="text/javascript" src="/js/src/scrollspy.js?v=5.1.4"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=5.1.4"></script>



  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=5.1.4"></script>



  


  




	





  





  












  

  <script type="text/javascript">
    // Popup Window;
    var isfetched = false;
    var isXml = true;
    // Search DB path;
    var search_path = "search.xml";
    if (search_path.length === 0) {
      search_path = "search.xml";
    } else if (/json$/i.test(search_path)) {
      isXml = false;
    }
    var path = "/" + search_path;
    // monitor main search box;

    var onPopupClose = function (e) {
      $('.popup').hide();
      $('#local-search-input').val('');
      $('.search-result-list').remove();
      $('#no-result').remove();
      $(".local-search-pop-overlay").remove();
      $('body').css('overflow', '');
    }

    function proceedsearch() {
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay"></div>')
        .css('overflow', 'hidden');
      $('.search-popup-overlay').click(onPopupClose);
      $('.popup').toggle();
      var $localSearchInput = $('#local-search-input');
      $localSearchInput.attr("autocapitalize", "none");
      $localSearchInput.attr("autocorrect", "off");
      $localSearchInput.focus();
    }

    // search function;
    var searchFunc = function(path, search_id, content_id) {
      'use strict';

      // start loading animation
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay">' +
          '<div id="search-loading-icon">' +
          '<i class="fa fa-spinner fa-pulse fa-5x fa-fw"></i>' +
          '</div>' +
          '</div>')
        .css('overflow', 'hidden');
      $("#search-loading-icon").css('margin', '20% auto 0 auto').css('text-align', 'center');

      $.ajax({
        url: path,
        dataType: isXml ? "xml" : "json",
        async: true,
        success: function(res) {
          // get the contents from search data
          isfetched = true;
          $('.popup').detach().appendTo('.header-inner');
          var datas = isXml ? $("entry", res).map(function() {
            return {
              title: $("title", this).text(),
              content: $("content",this).text(),
              url: $("url" , this).text()
            };
          }).get() : res;
          var input = document.getElementById(search_id);
          var resultContent = document.getElementById(content_id);
          var inputEventFunction = function() {
            var searchText = input.value.trim().toLowerCase();
            var keywords = searchText.split(/[\s\-]+/);
            if (keywords.length > 1) {
              keywords.push(searchText);
            }
            var resultItems = [];
            if (searchText.length > 0) {
              // perform local searching
              datas.forEach(function(data) {
                var isMatch = false;
                var hitCount = 0;
                var searchTextCount = 0;
                var title = data.title.trim();
                var titleInLowerCase = title.toLowerCase();
                var content = data.content.trim().replace(/<[^>]+>/g,"");
                var contentInLowerCase = content.toLowerCase();
                var articleUrl = decodeURIComponent(data.url);
                var indexOfTitle = [];
                var indexOfContent = [];
                // only match articles with not empty titles
                if(title != '') {
                  keywords.forEach(function(keyword) {
                    function getIndexByWord(word, text, caseSensitive) {
                      var wordLen = word.length;
                      if (wordLen === 0) {
                        return [];
                      }
                      var startPosition = 0, position = [], index = [];
                      if (!caseSensitive) {
                        text = text.toLowerCase();
                        word = word.toLowerCase();
                      }
                      while ((position = text.indexOf(word, startPosition)) > -1) {
                        index.push({position: position, word: word});
                        startPosition = position + wordLen;
                      }
                      return index;
                    }

                    indexOfTitle = indexOfTitle.concat(getIndexByWord(keyword, titleInLowerCase, false));
                    indexOfContent = indexOfContent.concat(getIndexByWord(keyword, contentInLowerCase, false));
                  });
                  if (indexOfTitle.length > 0 || indexOfContent.length > 0) {
                    isMatch = true;
                    hitCount = indexOfTitle.length + indexOfContent.length;
                  }
                }

                // show search results

                if (isMatch) {
                  // sort index by position of keyword

                  [indexOfTitle, indexOfContent].forEach(function (index) {
                    index.sort(function (itemLeft, itemRight) {
                      if (itemRight.position !== itemLeft.position) {
                        return itemRight.position - itemLeft.position;
                      } else {
                        return itemLeft.word.length - itemRight.word.length;
                      }
                    });
                  });

                  // merge hits into slices

                  function mergeIntoSlice(text, start, end, index) {
                    var item = index[index.length - 1];
                    var position = item.position;
                    var word = item.word;
                    var hits = [];
                    var searchTextCountInSlice = 0;
                    while (position + word.length <= end && index.length != 0) {
                      if (word === searchText) {
                        searchTextCountInSlice++;
                      }
                      hits.push({position: position, length: word.length});
                      var wordEnd = position + word.length;

                      // move to next position of hit

                      index.pop();
                      while (index.length != 0) {
                        item = index[index.length - 1];
                        position = item.position;
                        word = item.word;
                        if (wordEnd > position) {
                          index.pop();
                        } else {
                          break;
                        }
                      }
                    }
                    searchTextCount += searchTextCountInSlice;
                    return {
                      hits: hits,
                      start: start,
                      end: end,
                      searchTextCount: searchTextCountInSlice
                    };
                  }

                  var slicesOfTitle = [];
                  if (indexOfTitle.length != 0) {
                    slicesOfTitle.push(mergeIntoSlice(title, 0, title.length, indexOfTitle));
                  }

                  var slicesOfContent = [];
                  while (indexOfContent.length != 0) {
                    var item = indexOfContent[indexOfContent.length - 1];
                    var position = item.position;
                    var word = item.word;
                    // cut out 100 characters
                    var start = position - 20;
                    var end = position + 80;
                    if(start < 0){
                      start = 0;
                    }
                    if (end < position + word.length) {
                      end = position + word.length;
                    }
                    if(end > content.length){
                      end = content.length;
                    }
                    slicesOfContent.push(mergeIntoSlice(content, start, end, indexOfContent));
                  }

                  // sort slices in content by search text's count and hits' count

                  slicesOfContent.sort(function (sliceLeft, sliceRight) {
                    if (sliceLeft.searchTextCount !== sliceRight.searchTextCount) {
                      return sliceRight.searchTextCount - sliceLeft.searchTextCount;
                    } else if (sliceLeft.hits.length !== sliceRight.hits.length) {
                      return sliceRight.hits.length - sliceLeft.hits.length;
                    } else {
                      return sliceLeft.start - sliceRight.start;
                    }
                  });

                  // select top N slices in content

                  var upperBound = parseInt('1');
                  if (upperBound >= 0) {
                    slicesOfContent = slicesOfContent.slice(0, upperBound);
                  }

                  // highlight title and content

                  function highlightKeyword(text, slice) {
                    var result = '';
                    var prevEnd = slice.start;
                    slice.hits.forEach(function (hit) {
                      result += text.substring(prevEnd, hit.position);
                      var end = hit.position + hit.length;
                      result += '<b class="search-keyword">' + text.substring(hit.position, end) + '</b>';
                      prevEnd = end;
                    });
                    result += text.substring(prevEnd, slice.end);
                    return result;
                  }

                  var resultItem = '';

                  if (slicesOfTitle.length != 0) {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + highlightKeyword(title, slicesOfTitle[0]) + "</a>";
                  } else {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + title + "</a>";
                  }

                  slicesOfContent.forEach(function (slice) {
                    resultItem += "<a href='" + articleUrl + "'>" +
                      "<p class=\"search-result\">" + highlightKeyword(content, slice) +
                      "...</p>" + "</a>";
                  });

                  resultItem += "</li>";
                  resultItems.push({
                    item: resultItem,
                    searchTextCount: searchTextCount,
                    hitCount: hitCount,
                    id: resultItems.length
                  });
                }
              })
            };
            if (keywords.length === 1 && keywords[0] === "") {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-search fa-5x" /></div>'
            } else if (resultItems.length === 0) {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-frown-o fa-5x" /></div>'
            } else {
              resultItems.sort(function (resultLeft, resultRight) {
                if (resultLeft.searchTextCount !== resultRight.searchTextCount) {
                  return resultRight.searchTextCount - resultLeft.searchTextCount;
                } else if (resultLeft.hitCount !== resultRight.hitCount) {
                  return resultRight.hitCount - resultLeft.hitCount;
                } else {
                  return resultRight.id - resultLeft.id;
                }
              });
              var searchResultList = '<ul class=\"search-result-list\">';
              resultItems.forEach(function (result) {
                searchResultList += result.item;
              })
              searchResultList += "</ul>";
              resultContent.innerHTML = searchResultList;
            }
          }

          if ('auto' === 'auto') {
            input.addEventListener('input', inputEventFunction);
          } else {
            $('.search-icon').click(inputEventFunction);
            input.addEventListener('keypress', function (event) {
              if (event.keyCode === 13) {
                inputEventFunction();
              }
            });
          }

          // remove loading animation
          $(".local-search-pop-overlay").remove();
          $('body').css('overflow', '');

          proceedsearch();
        }
      });
    }

    // handle and trigger popup window;
    $('.popup-trigger').click(function(e) {
      e.stopPropagation();
      if (isfetched === false) {
        searchFunc(path, 'local-search-input', 'local-search-result');
      } else {
        proceedsearch();
      };
    });

    $('.popup-btn-close').click(onPopupClose);
    $('.popup').click(function(e){
      e.stopPropagation();
    });
    $(document).on('keyup', function (event) {
      var shouldDismissSearchPopup = event.which === 27 &&
        $('.search-popup').is(':visible');
      if (shouldDismissSearchPopup) {
        onPopupClose();
      }
    });
  </script>





  

  

  

  
  

  

  

  

</body>
</html>
